#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
跨平台WebDriver管理工具
支持Windows、macOS、Linux系统的自动驱动文件选择
"""

import os
import platform
from selenium.webdriver.edge.service import Service as EdgeService

class DriverManager:
    """WebDriver管理器，处理跨平台兼容性"""
    
    def __init__(self, driver_name="msedgedriver1"):
        """
        初始化驱动管理器
        
        Args:
            driver_name: 驱动文件的基础名称（不含扩展名）
        """
        self.driver_name = driver_name
        self.system = platform.system()
        
    def get_driver_filename(self):
        """根据操作系统获取正确的驱动文件名"""
        if self.system == "Windows":
            return f"{self.driver_name}.exe"
        else:  # Mac, Linux等
            return self.driver_name
    
    def get_driver_path(self):
        """获取驱动文件的绝对路径"""
        filename = self.get_driver_filename()
        return os.path.abspath(f"./{filename}")
    
    def check_driver_exists(self):
        """检查驱动文件是否存在"""
        driver_path = self.get_driver_path()
        return os.path.isfile(driver_path)
    
    def check_driver_permissions(self):
        """检查驱动文件权限"""
        driver_path = self.get_driver_path()
        if not self.check_driver_exists():
            return False
        return os.access(driver_path, os.X_OK)
    
    def get_driver_info(self):
        """获取驱动文件信息"""
        driver_path = self.get_driver_path()
        filename = self.get_driver_filename()
        
        info = {
            'system': self.system,
            'filename': filename,
            'path': driver_path,
            'exists': self.check_driver_exists(),
            'executable': False,
            'size': 0
        }
        
        if info['exists']:
            info['executable'] = self.check_driver_permissions()
            info['size'] = os.path.getsize(driver_path)
        
        return info
    
    def create_edge_service(self):
        """创建Edge WebDriver服务"""
        driver_path = self.get_driver_path()
        filename = self.get_driver_filename()
        
        # 检查文件是否存在
        if not self.check_driver_exists():
            error_msg = f"找不到驱动文件: {driver_path}"
            print(f"❌ {error_msg}")
            print(f"🔍 当前系统: {self.system}")
            print(f"🔍 期望的驱动文件名: {filename}")
            print("📝 请确保驱动文件存在并且文件名正确")
            raise FileNotFoundError(error_msg)
        
        # 检查执行权限
        if not self.check_driver_permissions():
            print(f"⚠️ 驱动文件没有执行权限: {driver_path}")
            if self.system != "Windows":
                print(f"💡 请运行: chmod +x {filename}")
        
        print(f"✅ 找到驱动文件: {driver_path}")
        return EdgeService(executable_path=driver_path)
    
    def find_alternative_drivers(self):
        """查找可能的替代驱动文件"""
        possible_files = [
            "msedgedriver1",
            "msedgedriver1.exe", 
            "msedgedriver",
            "msedgedriver.exe",
            "edgedriver",
            "edgedriver.exe"
        ]
        
        found_files = []
        for filename in possible_files:
            if os.path.isfile(filename):
                found_files.append(filename)
        
        return found_files
    
    def print_driver_status(self):
        """打印驱动状态信息"""
        info = self.get_driver_info()
        
        print(f"🔍 系统信息: {info['system']}")
        print(f"🔍 期望驱动文件: {info['filename']}")
        print(f"🔍 驱动路径: {info['path']}")
        
        if info['exists']:
            print(f"✅ 驱动文件存在")
            print(f"📊 文件大小: {info['size']:,} 字节 ({info['size']/1024/1024:.1f} MB)")
            
            if info['executable']:
                print(f"✅ 具有执行权限")
            else:
                print(f"⚠️ 缺少执行权限")
                if self.system != "Windows":
                    print(f"💡 请运行: chmod +x {info['filename']}")
        else:
            print(f"❌ 驱动文件不存在")
            
            # 查找替代文件
            alternatives = self.find_alternative_drivers()
            if alternatives:
                print(f"🔍 找到可能的替代文件:")
                for alt in alternatives:
                    print(f"   - {alt}")
                print(f"💡 建议将 {alternatives[0]} 重命名为 {info['filename']}")
            else:
                print(f"📝 请下载适合 {self.system} 系统的 Microsoft Edge WebDriver:")
                print("   https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/")

def get_edge_service(driver_name="msedgedriver1"):
    """
    便捷函数：获取Edge WebDriver服务
    
    Args:
        driver_name: 驱动文件的基础名称（不含扩展名）
    
    Returns:
        EdgeService: Edge WebDriver服务实例
    """
    manager = DriverManager(driver_name)
    return manager.create_edge_service()

def check_driver_compatibility(driver_name="msedgedriver1"):
    """
    便捷函数：检查驱动兼容性
    
    Args:
        driver_name: 驱动文件的基础名称（不含扩展名）
    
    Returns:
        bool: 驱动是否可用
    """
    manager = DriverManager(driver_name)
    manager.print_driver_status()
    return manager.check_driver_exists() and manager.check_driver_permissions()

if __name__ == "__main__":
    # 测试驱动管理器
    print("🧪 测试驱动管理器...")
    print("=" * 50)
    
    manager = DriverManager()
    manager.print_driver_status()
    
    print("\n" + "=" * 50)
    
    try:
        service = manager.create_edge_service()
        print("✅ 成功创建Edge服务")
    except Exception as e:
        print(f"❌ 创建Edge服务失败: {e}")
    
    print("\n🎯 测试完成")
